package kr.co.bettersoft.sendme.rest;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import kr.co.bettersoft.sendme.provider.SendMeInstall;
import kr.co.bettersoft.sendme.util.SendMeConstant;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

public class SendMeInstallRest {
	public static String TAG = SendMeInstallRest.class.getSimpleName();
	
	/**
	 * 설치한 친구 목록을 업데이트 한다.
	 * 
	 * @param sendMeInstall
	 * @return
	 */
	public String updateInstall(List<SendMeInstall> sendMeInstallList) {
		Log.i(TAG, "updateInstall");
		
		String url = SendMeConstant.SERVER_URL
			+ SendMeConstant.MAPPING_CONTROLLER
			+ SendMeConstant.INSTALL_CONTROLLER
			+ SendMeConstant.UPDATE_INSTALL;
		try {
			
			JSONArray parameterJsonArray = new JSONArray();
			
			for(int i=0; i<sendMeInstallList.size(); i++){
				
				SendMeInstall sendMeInstall = sendMeInstallList.get(i);
				
				JSONObject parameterJsonObject = new JSONObject();
				
				parameterJsonObject.put("phoneNumber", sendMeInstall.getPhoneNumber());
				parameterJsonObject.put("activateYn", sendMeInstall.getActivateYn());
				
				parameterJsonObject.put("modifyDate", sendMeInstall.getModifyDate());
				parameterJsonObject.put("registerDate", sendMeInstall.getRegisterDate());
				
				parameterJsonObject.put("sendMeMemberPhoneNumber", sendMeInstall.getSendMeMemberPhoneNumber());
				parameterJsonObject.put("totalCount", "");
				parameterJsonObject.put("result", "");
				
				parameterJsonArray.put(parameterJsonObject.toString());		 // jsonArray 에 jsonObject 를 담아서 서버로 리스트를 보낼때는 jsonObject 그대로 넣지 않고 toString() 으로 변환하여 담는다
								
			}
			
//			Log.d(TAG,"parameterJsonArray.toString():"+parameterJsonArray.toString());
			this.requestToServer(url, parameterJsonArray.toString());		// 서버로부터 결과 받지 않음
		} catch(Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * 설치여부 목록을 가져 온다.
	 * 
	 * @param sendMeInstall
	 * @return
	 */
	public List<SendMeInstall> selectInstallList(SendMeInstall sendMeInstall) {
		Log.i(TAG, "selectInstallList");
		
		String url = SendMeConstant.SERVER_URL
			+ SendMeConstant.MAPPING_CONTROLLER
			+ SendMeConstant.INSTALL_CONTROLLER
			+ SendMeConstant.SELECT_INSTALL_LIST;
		
		List<SendMeInstall> result = null;
		
		try {
			JSONObject parameterJsonObject = new JSONObject();
			
			parameterJsonObject.put("activateYn", sendMeInstall.getActivateYn());
			parameterJsonObject.put("sendMeMemberPhoneNumber", sendMeInstall.getSendMeMemberPhoneNumber());
			
			String resultStr = this.requestToServer(url, parameterJsonObject.toString());
			
			JSONArray resultJsonArray = new JSONArray(resultStr);
			result = new ArrayList<SendMeInstall>();		//	result = new ArrayList<SendMeInstall>();	// no data : [null] = 1개  // result.size()=0 , resultJsonArray.length()=1
			for(int i=0; i<resultJsonArray.length(); i++){				
				JSONObject resultJsonObject = resultJsonArray.getJSONObject(i);
				
				SendMeInstall tempSendMeInstall = new SendMeInstall();
				tempSendMeInstall.setPhoneNumber(resultJsonObject.getString("phoneNumber"));
				tempSendMeInstall.setNickName(resultJsonObject.getString("nickName"));
				result.add(tempSendMeInstall);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	/**
	 * http protocal 을 사용하는 서버 요청 공통 메소드.
	 * 요청 후 결과를 json string 으로 받아서 반환 한다.
	 * 
	 * @param url
	 * @param inputJsonString
	 * @return
	 */
	public String requestToServer(String url, String inputJsonString) {
		Log.i(TAG, "requestToServer");
		
		String result = "";
		
		try {
			URL postUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(inputJsonString.getBytes());
	        os.flush();
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	        		result = bufferedReader.readLine();
	        	}
	        }
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	/**
	 * http protocal 을 사용하는 서버 요청 공통 메소드.
	 * 요청 후 결과를 json string 으로 받아서 반환 한다.
	 * 
	 * @param url
	 * @param inputJsonString
	 * @return
	 */
	public String requestToServer2(String url, String inputJsonString) {
		Log.i(TAG, "requestToServer2");
		
		String result = "";
		try{
			URL postUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
			connection.setConnectTimeout(3000);
			connection.setDoOutput(true);
			connection.setInstanceFollowRedirects(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type", "application/json");
			
			OutputStream os = connection.getOutputStream();		 
			os.write(inputJsonString.getBytes("UTF-8"));
			os.flush();
			
			int responseCode = connection.getResponseCode();
			InputStream in =  connection.getInputStream();
			if(responseCode==200 || responseCode==204){
				// 결과를 처리.
				BufferedReader reader = new BufferedReader(new InputStreamReader(in), 8192);
				StringBuilder builder = new StringBuilder();
				String line =null;
				try {
					while((line=reader.readLine())!=null){
						builder.append(line).append("\n");		// 끝에 줄바꿈?
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				result = builder.toString();
			}
		}catch(Exception e){ 
			e.printStackTrace();
		}
		
		return result;
	}
}
